package com.tdam2012.grupo04.messageWeb;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

import com.tdam2012.grupo04.ContactsActivity;
import com.tdam2012.grupo04.data.ActividadesProvider;
import com.tdam2012.grupo04.data.MensajesProvider;
import com.tdam2012.grupo04.data.UsuariosProvider;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;

public class MessageWebService extends Service {

	private Handler handler;
	private List<MessageWeb> messagesList;
	private boolean newMessages = false;
	private NotificationManager mNotificationManager;
	private final IBinder mBinder = new LocalBinder();
	private static final String UsuarioWeb = "usuarioWeb";
	private static final String Usuario = "usuario";
	private String notTickerText;
	private String notTitle;
	private String notText;
	private String mensajeRecibido;
	 


	@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStart(intent, startId);
		newMessages=false;
		handler.removeCallbacks(checkForMessages);
		handler.postDelayed(checkForMessages, 500);
		String ns=Context.NOTIFICATION_SERVICE;
        mNotificationManager = (NotificationManager) getSystemService(ns);
        String[] strings = (String[]) intent.getSerializableExtra(ContactsActivity.STRINGS);
        notTickerText=strings[0];
    	notTitle=strings[1];
    	notText=strings[2];
    	mensajeRecibido=strings[3];
        return START_STICKY;
    }
	
	private Runnable checkForMessages = new Runnable() {
		public void run() {
			checkMessages();
			if (newMessages) {
				sendNotification(notTickerText,notTitle,notText);
				newMessages=false;
			}
			handler.postDelayed(this, 2000);
		}
	};
	
	private void checkMessages() {
		List<MessageWeb> list = null;
		SharedPreferences preferences = getSharedPreferences(UsuarioWeb, MODE_PRIVATE);
    	String usuarioLocal = preferences.getString(Usuario, "");
		Date date = null;
		String timestamp = "";
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-03:00")); 
		SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		if(getMessagesCount(usuarioLocal,"0")==0)
		{
			timestamp = postFormater.format(c.getTime());
		}
		else
		{
	        try {
	        	if(getMessagesCount(usuarioLocal,"1")!=0){
	        		date = postFormater.parse(getLastMessageDate(usuarioLocal,"1"));
					date.setSeconds(date.getSeconds()+1);
	        	}
	        	else {
	        		date = postFormater.parse(getFirstMessageDate(usuarioLocal,"0"));
					date.setSeconds(date.getSeconds()-3);
	        	}
	        	timestamp = postFormater.format(date);
			} catch (ParseException e) {timestamp = postFormater.format(c.getTime());}
		}
		try {
			ServerConnection connection = new ServerConnection();
			list = connection.parseGet(usuarioLocal, timestamp);
			if (list.size()>0) {
				Iterator<MessageWeb> iter = list.iterator();
				while(iter.hasNext())
				{
					MessageWeb mesg = iter.next();
					ContentResolver cr = getContentResolver();
					ContentValues args = new ContentValues();
				    args.put(MensajesProvider.COL_LEIDO, "1");
				    String codigo = mesg.getCodigo();
				    String[] condiciones = new String[] {codigo}; //ID Mensaje a modificar
			    	cr.update(MensajesProvider.CONTENT_URI, args, null, condiciones);
			    	list.add(mesg);
			    	String idContacto = getContactId(mesg.getUsuarioLocal());
			    	registerMessageAction(mensajeRecibido, idContacto);
			    	newMessages=true;
				}
			}
		} catch (Exception e) { }
	}
	
	private void registerMessageAction(String estadoActividad, String idContacto){
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-03:00")); 
		SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss" ); 
		ContentValues cv2 = new ContentValues();				
		cv2.put(ActividadesProvider.COL_TIPO, estadoActividad);
		cv2.put(ActividadesProvider.COL_ID, idContacto);
		cv2.put(ActividadesProvider.COL_FECHA, postFormater.format(c.getTime()));
		getContentResolver().insert(ActividadesProvider.CONTENT_URI, cv2);
	}
	
	private int getMessagesCount(String usuarioLocal, String estado) {
		try {
			ContentResolver cr = getContentResolver();
	    	String[] condiciones = new String[] {usuarioLocal, "", estado};
	    	Cursor cursor = cr.query(MensajesProvider.CONTENT_URI, null, null, condiciones, null);
	    	int count = cursor.getCount();
	    	cursor.close();
			return count;
		} catch (Exception e) {
			return 0;
		}
		
	}
	
	private String getLastMessageDate(String usuarioLocal, String estado) {
		try {
			ContentResolver cr = getContentResolver();
	    	String[] condiciones = new String[] {usuarioLocal,"", estado};
	    	Cursor cursor = cr.query(MensajesProvider.CONTENT_URI, null, null, condiciones, null);
	    	cursor.moveToLast();
	    	String fecha = cursor.getString(2);
			cursor.close();
			return fecha;
		} catch (Exception e) {
			return "";
		}
	}
	
	private String getFirstMessageDate(String usuarioLocal, String estado) {
		try {
			ContentResolver cr = getContentResolver();
	    	String[] condiciones = new String[] {usuarioLocal,"", estado};
	    	Cursor cursor = cr.query(MensajesProvider.CONTENT_URI, null, null, condiciones, null);
	    	cursor.moveToFirst();
	    	String fecha = cursor.getString(2);
			cursor.close();
			return fecha;
		} catch (Exception e) {
			return "";
		}
	}

	private String getContactId(String user) {
    	String nombre="";
    	ContentResolver cr = getContentResolver();
    	String[] condiciones = new String[] {"", user};
		Cursor cursor = cr.query(UsuariosProvider.CONTENT_URI, null, null, condiciones, null);
		if (cursor.getCount()>0){
			while (cursor.moveToNext()) {
				nombre=cursor.getString(1).toString();
			}
		}
		cursor.close();
		return nombre;
	}
	
	private void sendNotification(String _tickerText, String _title, String _text){
		Notification notification = new Notification(android.R.drawable.sym_action_chat, _tickerText, System.currentTimeMillis());
		Intent intent = new Intent();
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
    	notification.setLatestEventInfo(this, _title, _text, contentIntent);
    	notification.flags = Notification.FLAG_AUTO_CANCEL;
    	mNotificationManager.notify(2, notification);
	}
	
	public void clearMessages() {
		if (messagesList == null) {
			messagesList = new ArrayList<MessageWeb>();
		}
		messagesList.clear();
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		handler = new Handler();
		messagesList = new ArrayList<MessageWeb>();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}	

    public class LocalBinder extends Binder {
    	public MessageWebService getService() {
            return MessageWebService.this;
        }
    }

	

}
